package org.xtlgen;

import java.awt.geom.Rectangle2D;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Element;

/**
 * Represents a simple Rectangle in the XtlGen system.
 * <p>
 * A Rectangle must be specified like this:
 * </p>
 * <pre>
 * &lt;Rectangle x="[x_position]" y="[y_position]" width="[width] height="[height]" &gt;
 *   [subshapes]
 * &lt;/Rectangle&gt;
 * </pre>
 * or this:
 * <pre>
 * &lt;Rectangle x="[x_position]" y="[y_position]" width="[width] height="[height]" /&gt;
 * </pre>
 * in the configuration file.
 */
public class Rectangle extends ClosedShape {
  /**
   * Construct a Rectangle.
   *
   * @param parent  the parent Shape, null allowed
   * @param params  parameters for this Shape as read from the config file
   */
  public Rectangle(Shape parent, Element params) {
    super(parent, params);
  }

  /**
   * Create the encapsulated AWT Rectangle.
   *
   * @param params  parameters for this Shape as read from the config file
   *
   * @return An AWT Rectangle.
   *
   * @throws IllegalArgumentException if one of the required parameters cannot
   *         be found on the given params object.
   */
  protected java.awt.Shape createAWTShape(Element params) {
    java.awt.Shape result = null;
    NamedNodeMap attributes = params.getAttributes();
    
    if (attributes == null) {
      throw new IllegalArgumentException(
        "Rectangle requires the x, y, width and height attributes");
    }
    else {
      try {
        ShapeAttributes shapeAttributes = new ShapeAttributes(attributes);
        result = new Rectangle2D.Double(
          shapeAttributes.getDouble("x"),
          shapeAttributes.getDouble("y"),
          shapeAttributes.getDouble("width"),
          shapeAttributes.getDouble("height"));
      }
      catch(IllegalArgumentException e) {
        throw new IllegalArgumentException("Rectangle: " + e.getMessage());
      }
    }

    return result;
  }

  /**
   * Get the list of child nodes in params.
   *
   * @return The child node list.
   */
  protected NodeList getChildren(Element params) {
    return params.getChildNodes();
  }
  
  /*
   * Static block of code used to register a ShapeFactory for Rectangles.
   */
  static {
    Shape.registerShapeFactory(
      "Rectangle",
      new Shape.ShapeFactory() {
        public Shape makeShape(Shape parent, Element params) {
          return new Rectangle(parent, params);
        }
      });
  }
}